package com.lagou.client;

import com.lagou.handler.UserClientHandler;
import com.lagou.protocol.RpcRequest;
import com.lagou.serializer.JSONSerializer;
import com.lagou.serializer.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.I0Itec.zkclient.ZkClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 13771
 * @date 2020/8/31 11:30
 * @description
 */
public class RPCConsumer {
    //1.创建一个线程池对象  --它要处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器  UserClientHandler
    private static UserClientHandler userClientHandler;

    //客户端发起请求总数
    private static  int reqCount = 1;

    //服务端个数
    private static int serverCount =0;

    public static ZkClient zkClient = new ZkClient("127.0.0.1:2181");

    //3.初始化客户端
    public static void initClient() throws InterruptedException {
        //1) 初始化UserClientHandler
        userClientHandler = new UserClientHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });



        //父节点路径
        //ZkClient zkClient = new ZkClient("127.0.0.1:2181",2000,5000);
        //服务端集群
        List<String> serverList = new ArrayList<String>();
        String root = "/rpcServer";
        List<String> childrens = zkClient.getChildren(root);
        for (String children : childrens){
            String path = root + "/" +children; //子节点完整路径
            String nodeValue = zkClient.readData(path);
            serverList.add(nodeValue);
        }
        //服务端数量赋值
        serverCount = serverList.size();
        //请求次数对服务端总数取模，得到集合的index值，用于负载均衡
        String s = serverList.get(reqCount % serverCount);
        System.out.println("客户端第"+reqCount+"次请求==>>>"+"对应服务端"+s);
        String[] split = s.split(":");
        String ip = split[0];
        int port = Integer.parseInt(split[1]);

        //注册监听
//        zkClient.subscribeChildChanges(root, new IZkChildListener() {
//            public void handleChildChange(String s, List<String> list) throws Exception {
//                initClient();
//            }
//        });
        try {
            bootstrap.connect(ip,port).sync();
        }catch (Exception e){
//            reqCount++;
            initClient();
        }
        reqCount++;
    }

    //4.编写一个方法，使用JDK的动态代理创建对象
    //serviceClass 接口类型，根据哪个接口子类代理对象； providerParam："UserService#sayHello#"
    public static Object creatProxy(final Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //1）初始化客户端client
 //               if (userClientHandler ==null){
                    initClient();
 //               }

                //2) 给UserClientHandler 设置param参数 封装RpcRequest
                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameterTypes(method.getParameterTypes());
                rpcRequest.setParameters(args);
                userClientHandler.setParam(rpcRequest);

                //3）使用线程池，开启一个线程处理call() 写操作，并返回结果
                Object result = executorService.submit(userClientHandler).get();

                //4）return 结果
                return result;
            }
        });
    }
}
